package ink.xiaobaibai.controller.free;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ink.xiaobaibai.autoConfig.roleResources.ResourcesRoleMapping;
import ink.xiaobaibai.common.FreeDeviceStatus;
import ink.xiaobaibai.common.MyRole;
import ink.xiaobaibai.common.SelectFreeDeviceBo;
import ink.xiaobaibai.entity.FreeOxygenDevice;
import ink.xiaobaibai.entity.FreeOzoneDevice;
import ink.xiaobaibai.response.ResponseFormat;
import ink.xiaobaibai.service.IAdminUserService;
import ink.xiaobaibai.service.IFreeOxygenDeviceService;
import ink.xiaobaibai.service.IFreeOzoneDeviceService;
import ink.xiaobaibai.units.MySecurity;
import ink.xiaobaibai.valited.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @description: 免费机器氧气机控制层
 * @author: 小白白
 * @create: 2021-07-20
 **/

@RestController
@RequestMapping("/free/oxygen")
@Api(tags = "免费氧气机器接口")
@CrossOrigin
public class FreeOxygenDeviceController {

    @Autowired
    private IFreeOxygenDeviceService freeOxygenDeviceService;

    @Autowired
    private IFreeOzoneDeviceService freeOzoneDeviceService;

    @Autowired
    private IAdminUserService adminUserService;

    /**
     * 查询氧气机
     */
    @PostMapping("/list")
    @ApiOperation("查询自己的氧气机")
    public ResponseFormat list(@RequestBody @Validated SelectFreeDeviceBo selectFreeDeviceBo) {
        Integer userId = MySecurity.getUserId();
        QueryWrapper<FreeOxygenDevice> q1 = new QueryWrapper<>();
        if (!MySecurity.isPower(MyRole.POWER_FREE)) {
            String role = MySecurity.getRole();
            if (role.equals(MyRole.DISTRIBUTOR) && !MySecurity.getRoles().contains(MyRole.POWER_FREE)) {
                q1.eq("admin_user_id", userId);
            }
            if (role.equals(MyRole.AGENT) && !MySecurity.getRoles().contains(MyRole.POWER_FREE)) {
                q1.eq("dep_id", this.adminUserService.getDepId(userId));
            }
        }
        if (selectFreeDeviceBo.getAdminUserId() != null) {
            q1.eq("admin_user_id", selectFreeDeviceBo.getAdminUserId());
        }
        if (selectFreeDeviceBo.getAddress() != null) {
            q1.likeRight("address", selectFreeDeviceBo.getAddress());
        }
        if (selectFreeDeviceBo.getProvinceCity() != null) {
            q1.likeRight("province_city", selectFreeDeviceBo.getProvinceCity());
        }
        Page<FreeOxygenDevice> page = this.freeOxygenDeviceService.page(new Page<>(selectFreeDeviceBo.getPageNum(), selectFreeDeviceBo.getPageSize()), q1);
        return ResponseFormat.success(page);
    }

    /**
     * 增加氧气机
     */
    @PostMapping("/add")
    @ApiOperation("增加免费氧气机")
    @ResourcesRoleMapping(resourceName = "增加免费氧气机", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_FREE})
    public ResponseFormat addOxygenDevice(@RequestBody @Validated FreeOxygenDevice freeOxygenDevice) {
        Integer userId = MySecurity.getUserId();
        // 校验机器码是否重复
        if (this.existDeviceCode(freeOxygenDevice.getDeviceCode())) {
            return ResponseFormat.fail("机器码重复");
        }
        if (freeOxygenDevice.getAdminUserId() == null) {
            freeOxygenDevice.setDepId(this.adminUserService.getDepId(userId));
            freeOxygenDevice.setAdminUserId(userId);
        } else {
            if (!this.adminUserService.existsUser(freeOxygenDevice.getAdminUserId())) {
                return ResponseFormat.fail("绑定用户不存在");
            }
            freeOxygenDevice.setDepId(this.adminUserService.getDepId(freeOxygenDevice.getAdminUserId()));
        }
        freeOxygenDevice.setStatus(FreeDeviceStatus.FREE.getStatus());
        this.freeOxygenDeviceService.save(freeOxygenDevice);
        return ResponseFormat.success();
    }

    /**
     * 修改氧气机
     */
    @PutMapping("/update")
    @ApiOperation("修改免费氧气机")
    @ResourcesRoleMapping(resourceName = "修改免费氧气机", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_FREE})
    public ResponseFormat updateOxygenDevice(@RequestBody @Validated(UpdateGroup.class) FreeOxygenDevice freeOxygenDevice) {
        Integer userId = MySecurity.getUserId();
        FreeOxygenDevice dbDevice = this.freeOxygenDeviceService.getById(freeOxygenDevice.getId());
        if (!dbDevice.getDeviceCode().equals(freeOxygenDevice.getDeviceCode()) && this.existDeviceCode(freeOxygenDevice.getDeviceCode())) {
            return ResponseFormat.fail("机器码重复");
        }
        if (freeOxygenDevice.getAdminUserId() != null && !StringUtils.equals(String.valueOf(dbDevice.getAdminUserId()), String.valueOf(freeOxygenDevice.getAdminUserId()))) {
            if (!this.adminUserService.existsUser(freeOxygenDevice.getAdminUserId())) {
                return ResponseFormat.fail("绑定用户不存在");
            }
            freeOxygenDevice.setDepId(this.adminUserService.getDepId(freeOxygenDevice.getAdminUserId()));
        }
        freeOxygenDevice.setDepId(this.adminUserService.getDepId(userId));
        freeOxygenDevice.setAdminUserId(userId);
        return this.freeOxygenDeviceService.updateById(freeOxygenDevice) ? ResponseFormat.success() : ResponseFormat.fail("未知错误");
    }

    /**
     * 删除氧气机
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除免费氧气机")
    @ResourcesRoleMapping(resourceName = "删除免费氧气机", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_FREE})
    public ResponseFormat deleteOxygenDevice(@PathVariable("id") Integer deviceId) {
        QueryWrapper<FreeOzoneDevice> q1 = new QueryWrapper<>();
        q1.eq("oxygen_id", deviceId);
        if (this.freeOzoneDeviceService.count(q1) != 0) {
            return ResponseFormat.fail("还有臭氧机绑定着此机器,请解除绑定后操作");
        }
        this.freeOxygenDeviceService.removeById(deviceId);
        return ResponseFormat.success();
    }

    // 机器码是否已经存在
    private boolean existDeviceCode(String deviceCode) {
        QueryWrapper<FreeOxygenDevice> q1 = new QueryWrapper<>();
        q1.eq("device_code", deviceCode);
        return this.freeOxygenDeviceService.count(q1) >= 1;
    }

}
